package com.oa.web.action;

import com.oa.utils.DBUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@WebServlet({"/user/login","/user/exit"})
public class UserServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String servletPath = request.getServletPath();
        if("/user/login".equals(servletPath)){
            doLogin(request,response);
        }else if("/user/exit".equals(servletPath)) {
            doExit(request,response);
        }
    }


    protected void doExit(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 获取session对象，销毁session
        HttpSession session = request.getSession();
        if(session != null){
            // 手动销毁session对象
            session.invalidate();

            // 跳转到登陆页面
            response.sendRedirect(request.getContextPath());
        }
    }
    protected void doLogin(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        /*
            验证用户名和密码是否正确
            获取用户名和密码，查数据库是否匹配，不匹配则登录失败，匹配则登陆成功
        */
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        boolean success = false;
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            conn = DBUtil.getConnection();
            String sql = "select * from t_user where username=? and password=?";
            ps = conn.prepareStatement(sql);
            ps.setString(1,username);
            ps.setString(2,password);

            rs = ps.executeQuery();
            // 这里不需要while,因为最多查出一条数据
            if(rs.next()){
                success = true;
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            DBUtil.close(conn, ps, rs);
        }

        if (success){
            // 获取session对象,（这里是登录的业务处理，必须获取session，没有session也得新建，所以不能加false）
            HttpSession session = request.getSession();
            session.setAttribute("username",username);

            // 登陆成功
            response.sendRedirect(request.getContextPath() + "/dept/list");
        }else{
            // 登陆失败
            response.sendRedirect(request.getContextPath() + "/loginError.jsp");
        }
    }
}
